<template>
    <div class="risk-deviation-query">
        <!-- 搜索框 -->
        <div class="deviation-search deviation-box">
            <el-form label-width="110px">
                <el-row class="search-box">
                    <el-col :span="5">
                        <el-form-item label="风控指令序号:">
                            <el-input placeholder="请输入" v-model="queryForm.instructionNo" style="width: 100%" size="mini" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="条目编号:">
                            <el-input placeholder="请输入" v-model="queryForm.entryCode" style="width: 100%" size="mini" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="恒生指令序号:">
                            <el-input
                                placeholder="请输入"
                                v-model="queryForm.dailyInstructionNo"
                                style="width: 100%"
                                size="mini"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="风险说明:">
                            <el-input placeholder="请输入" v-model="queryForm.entryName" style="width: 100%" size="mini" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="指令状态:">
                            <el-select v-model="queryForm.instStatus" disabled size="mini" clearable style="width: 100%">
                                <el-option label="已下达成功" value="1"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="触警类型:">
                            <el-select v-model="queryForm.thresholdTypes" size="mini" multiple collapse-tags clearable style="width: 100%">
                                <el-option v-for="(item, index) in ThresholdTypeArr" :key="index" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item class="checkBoxItem">
                            <el-checkbox v-model="queryForm.exceedThreshold" @change="queryTableDataList('userAction')"></el-checkbox>
                            偏离度≥<el-input v-model="deviationValue" @input="handleDeviationRatio" size="mini" style="width: 70px"></el-input>%
                        </el-form-item>

                        <el-form-item label="条目组:">
                            <el-select v-model="queryForm.entryGroups" size="mini" filterable clearable multiple collapse-tags style="width: 100%">
                                <el-option v-for="item in computedEntryGroups" :key="item.groupCode" :label="item.groupCode" :value="item.groupCode">
                                    <span style="float: left">{{ item.groupCode + ' ' + item.groupName }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <!-- <el-form-item label="条目标签:">
                            <el-select v-model="queryForm.tagIds" size="mini" clearable multiple collapse-tags style="width: 100%">
                                <el-option v-for="item in computedEntryTags" :key="item.value" :label="item.label" :value="item.value">
                                    <span style="float: left">{{ item.value + ' ' + item.label }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                        <div class="operate">
                            <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
                            <el-button size="mini" type="primary" @click="handleReset">重置</el-button>
                            <el-button size="mini" type="primary" @click="layoutDialog = true">布局设置</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 数据列表 -->
        <div class="deviation-table deviation-box">
            <div class="table-box">
                <!-- <RiskTableP ref="risk-table" :tableConfig="tableConfig" :tableData="tableData" :column="tableColumns" v-loading="tableLoading">
                </RiskTableP> -->
                <vxe-table
                    :data="tableData"
                    :key="tableKey + 'tableKey'"
                    :cell-style="getCellStyle"
                    v-loading="tableLoading"
                    border
                    stripe
                    resizable
                    :auto-resize="true"
                    show-footer
                    :sort-config="{ defaultSort: { field: '', order: '' }, remote: true }"
                    :filter-config="{ remote: true }"
                    highlight-current-row
                    @sort-change="handleTableSortChange"
                    @filter-change="handleFilterChange"
                    ref="xTable"
                    show-header-overflow="tooltip"
                    header-align="center"
                    height="100%"
                >
                    <!-- <vxe-table-column title="操作" field="operate" show-overflow min-width="80" fixed="right">
                        <template slot-scope="scope">
                            <RiskIconButton type="primary" topTitle="详情" icon="el-icon-view" @on-click="handleBtnLook(scope.row)"></RiskIconButton>
                        </template>
                    </vxe-table-column> -->
                    <vxe-column
                        v-for="(item, index) in showFieldList"
                        :field="item.id"
                        :title="item.content"
                        :key="index"
                        :filters="item.filters"
                        :filter-render="{ name: 'FilterInput' }"
                        :min-width="item.minWidth || '150px'"
                        :fixed="item.fixed"
                        show-overflow
                        sortable
                    >
                        <template #filter="{ $panel, column }" v-if="item.filterType === 'search'">
                            <div>
                                <el-input
                                    ref="searchInput"
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </div>
                        </template>
                        <template slot-scope="scope">
                            <span v-if="item.id == 'thresholdType'">
                                <StatusTag :key="scope.row.thresholdType" :code="scope.row.thresholdType"></StatusTag>
                            </span>
                            <span v-else-if="item.id == 'entryCode'">
                                <span :style="getEntryCodeColor(scope.row.tagKeyNames)">{{ scope.row.entryCode }}</span>
                            </span>
                            <span v-else-if="item.id == 'deviationValue'">
                                <el-tooltip :disabled="!scope.row.remark" class="item" effect="dark" :content="scope.row.remark" placement="top">
                                    <span v-if="scope.row.exceedConfigValue" style="color: red">{{ scope.row.deviationValueShow }}</span>
                                    <span v-else-if="!scope.row.deviationValue && scope.row.deviationValueShow" style="color: #f5a43a">{{
                                        scope.row.deviationValueShow
                                    }}</span>
                                    <span v-else>{{ scope.row.deviationValueShow || '--' }}</span>
                                </el-tooltip>
                            </span>

                            <span v-else-if="item.id == 'compareType'">{{ compareDirectionPojo[scope.row.compareType] }}</span>
                            <span v-else-if="item.id == 'errorValid'">{{ errorValidPojo[scope.row.errorValid] }}</span>
                            <span v-else-if="item.id == 'instStatus'">{{ instStatusPojo[scope.row.instStatus] }}</span>
                            <!-- <span v-else-if="item.id == 'operate'">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        topTitle="详情"
                                        icon="el-icon-view"
                                        @on-click="handleBtnLook(scope.row)"
                                    ></RiskIconButton>
                                </template>
                            </span> -->
                            <span v-else>
                                {{ scope.row[item.id] !== undefined && (scope.row[item.id] + '').trim() ? scope.row[item.id] : '--' }}
                            </span>
                        </template>
                    </vxe-column>

                    <vxe-column title="操作" show-overflow width="80" fixed="right">
                        <template #default="{ row }">
                            <RiskIconButton type="primary" topTitle="详情" icon="el-icon-view" @on-click="handleBtnLook(row)"></RiskIconButton>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
            <div class="remark" style="color: gray; float: left; margin: 5px">
                <span
                    >* 实时风险偏离度字段:<span style="color: #f5a43a">黄色</span>表示无法进行偏离度计算，<span style="color: red">红色</span
                    >表示偏离度大于等于{{ deviationValue + '%' }}</span
                >
            </div>
            <RiskPagination :paging="queryForm.paging" @page-change="handlePageChange"></RiskPagination>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="RISK_DEVIATION"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import { getTableLayout } from '@/common/api/commonApi';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { TableConfigVO, VueObject } from '@/common/vo';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import DictionConstUtil from '@/utils/diction-const-util';
import { accDiv, changeOptions, numberFormat } from '@/utils/tools';
import { getSystem, setSystem } from '@/utils/user-util';
import { Vue, Component } from 'vue-property-decorator';
import VXETable from 'vxe-table';

// 创建一个简单的输入框筛选
VXETable.renderer.add('FilterInput', {
    // 重置数据方法
    filterResetMethod({ options }) {
        options.forEach(option => {
            option.data = '';
        });
    },
    // 重置筛选复原方法（当未点击确认时，该选项将被恢复为默认值）
    filterRecoverMethod({ option }) {
        option.data = '';
    },
    // 筛选方法
    filterMethod({ option, row, column }) {
        const { data } = option;
        const cellValue = row[column.property];
        if (cellValue) {
            return cellValue.indexOf(data) > -1;
        }
        return false;
    },
});
@Component({
    name: 'RiskDeviationQuery',
    components: {
        RiskPagination,
        RiskTableP,
        RiskTableLayout,
        RiskIconButton,
        StatusTag,
    },
})
export default class RiskDeviationQuery extends Vue {
    numberFormat = numberFormat;
    // 搜索参数表单
    queryForm: any = {
        instructionNo: '',
        dailyInstructionNo: '',
        entryCode: '',
        entryName: '',
        instStatus: '1',
        thresholdTypes: [],
        entryGroups: [],
        compareTypes: [],
        errorValids: [],
        errorMessage: '',
        fundCode: '',
        fundName: '',
        assetCode: '',
        assetName: '',
        fundAccountCode: '',
        fundAccountName: '',
        stockCode: '',
        stockName: '',
        exceedThreshold: false,
        sort: {
            field: '',
            order: '',
        },
        paging: {
            currentPage: 1,
            pageSize: 50,
            total: 0,
        },
        // tagIds: [],
    };
    // 分页参数
    pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    tableLoading: boolean = false;
    tableData: any[] = []; // 表格数据
    tableDataKey: number = 0;
    layoutDialog: boolean = false; // 试算结果表布局设置
    // itemTagsStorage: any[] = []; // 条目标签下拉数据
    // 触警类型
    ThresholdType = {
        '0': '合规',
        '1': '警告',
        '2': '送审',
        '3': '禁止',
    };
    // 触警类型
    ThresholdTypeArr: any[] = [
        { value: '0', label: '合规' },
        { value: '1', label: '警告' },
        { value: '2', label: '送审' },
        { value: '3', label: '禁止' },
    ];
    // 条目比较方向
    compareDirectionPojo: any = {};
    errorValidPojo: any = {
        '0': '否',
        '1': '是',
    };
    // 指令状态
    instStatusPojo = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
    };
    // 全部表格列
    tableColumns: any[] = [
        {
            content: '风控指令序号',
            id: 'instructionNo',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],

            search: true,
            minWidth: '150',
        },
        {
            content: '恒生指令序号',
            id: 'dailyInstructionNo',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],

            search: true,
            minWidth: '150',
        },
        { content: '恒生指令批号', id: 'batchNo', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        {
            content: '指令状态',
            id: 'instStatus',
            sortable: true,
            filterType: 'funnel',
            filters: [{ label: '已下达成功', value: '1' }],
            align: 'center',
            minWidth: '150',
        },
        {
            content: '条目编号',
            id: 'entryCode',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
            minWidth: '150',
        },
        { content: '风险说明', id: 'entryName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        {
            content: '触警类型',
            id: 'thresholdType',
            sortable: true,
            filterType: 'funnel',
            filters: this.ThresholdTypeArr,
            align: 'center',
            minWidth: '150',
        },
        {
            content: '条目触发阈值',
            id: 'thresholdValue',
            sortable: true,
            align: 'right',
            minWidth: '150',
        },
        {
            content: '风控计算结果',
            id: 'calculateValue',
            sortable: true,
            align: 'right',
            minWidth: '150',
        },
        { content: '恒生计算结果', id: 'o32Value', sortable: true, align: 'right', minWidth: '150' },
        {
            content: '偏离度(%)',
            id: 'deviationValue',
            sortable: true,
            align: 'right',
            minWidth: '200',
        },
        // {
        //     content: '条目标签',
        //     id: 'tagIds',
        //     sortable: true,
        //     align: 'center',
        //     minWidth: '140',
        //     filterType: 'funnel',
        //     filters: this.itemTagsStorage,
        // },
        {
            content: '条目比较方向',
            id: 'compareType',
            sortable: true,
            filterType: 'funnel',
            filters: [
                { label: '大于', value: '0' },
                { label: '小于', value: '1' },
                { label: '大于等于', value: '2' },
                { label: '小于等于', value: '3' },
                { label: '等于', value: '4' },
                { label: '不等于', value: '5' },
                { label: '无', value: '6' },
            ],
            align: 'center',
            minWidth: '150',
        },
        {
            content: '计算逻辑',
            id: 'calLogicShow',
            sortable: true,
            minWidth: '150',
        },
        {
            content: '是否报错',
            id: 'errorValid',
            sortable: true,
            filterType: 'funnel',
            filters: [
                { label: '否', value: '0' },
                { label: '是', value: '1' },
            ],
            minWidth: '150',
            align: 'center',
        },
        { content: '报错信息', id: 'errorMessage', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '产品代码', id: 'fundCode', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '产品名称', id: 'fundName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        {
            content: '资产单元编号',
            id: 'assetCode',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],

            minWidth: '150',
        },
        {
            content: '资产单元名称',
            id: 'assetName',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],

            minWidth: '150',
        },
        {
            content: '组合编码',
            id: 'fundAccountCode',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
            minWidth: '150',
        },
        {
            content: '组合名称',
            id: 'fundAccountName',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
            minWidth: '150',
        },
        { content: '证券代码', id: 'stockCode', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '证券名称', id: 'stockName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        // { content: '操作', id: 'operate', minWidth: '80', fixed: 'right' },
    ];
    showFieldList: any[] = []; // 要显示的表格列
    // 默认显示表格列
    defaultSelectedFieldList: any[] = [
        {
            content: '风控指令序号',
            id: 'instructionNo',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
            search: true,
            minWidth: '150',
        },
        {
            content: '恒生指令序号',
            id: 'dailyInstructionNo',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
            search: true,
            minWidth: '150',
        },
        { content: '风险说明', id: 'entryName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        {
            content: '条目触发阈值',
            id: 'thresholdValue',
            sortable: true,
            align: 'right',
            minWidth: '150',
        },
        {
            content: '风控计算结果',
            id: 'calculateValue',
            sortable: true,
            align: 'right',
            minWidth: '150',
        },
        { content: '恒生计算结果', id: 'o32Value', sortable: true, align: 'right', minWidth: '150' },
        { content: '产品代码', id: 'fundCode', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '产品名称', id: 'fundName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '证券代码', id: 'stockCode', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        { content: '证券名称', id: 'stockName', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        // { content: '操作', id: 'operate', minWidth: '80', fixed: 'right' },
    ];
    selectedFieldList: any[] = []; // 已选择字段列表
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '条目编号', id: 'entryCode', sortable: true, filterType: 'search', filters: [{ data: '' }], minWidth: '150' },
        {
            content: '偏离度(%)',
            id: 'deviationValue',
            sortable: true,

            minWidth: '200',
        },
        // { content: '操作', id: 'operate', minWidth: '80', fixed: 'right' },
    ];
    tableConfig: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    columns: any[] = [];
    entryGroupList: any[] = []; // 条目组下拉数据
    clickRecord: any = {}; // 点击行
    filterList: any[] = [];
    tableKey: number = 0;
    deviationValue: any = null;
    currentRow: any = {};

    async mounted() {
        await this.queryLayout();
        this.queryEntryGroupData();
        // this.queryEntryTagData();
        this.queryTableDataList();
        await this.getDeviationValue();
        this.compareDirectionPojo = DictionConstUtil.CompareDirection;
    }

    // 通知岗位已选项前置
    get computedEntryGroups() {
        let entryGroups = changeOptions(this.queryForm.entryGroups, this.entryGroupList, 'groupCode');
        return entryGroups;
    }

    // 条目标签已选项前置
    // get computedEntryTags() {
    //     let tagIds = changeOptions(this.queryForm.tagIds, this.itemTagsStorage, 'value');
    //     return tagIds;
    // }

    // 查询静态是否展示错误类型
    async getDeviationValue() {
        // let values;
        let values = getSystem() || [];
        if (!getSystem().length) {
            await new Promise((resolve, reject) => {
                this.$axios
                    .get('/systemParam/list')
                    .then((res: any) => {
                        values = res;
                        setSystem(values);
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        }
        // 偏离度范围设定值
        let param = values.find(item => item.paramKey == 'RISK_RESULT_DEVIATION_VALUE')?.paramValue;
        this.deviationValue = param * 100;
    }

    // 获取页面布局信息
    async queryLayout() {
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout('RISK_DEVIATION')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            let list: any;
            try {
                list = JSON.parse(resList);
            } catch (err) {
                list = resList;
            }
            this.selectedFieldList = [];
            list.forEach(ele => {
                const obj = this.tableColumns.find(item => item.id == ele.id);
                obj && this.selectedFieldList.push(obj);
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.selectedFieldList = this.defaultSelectedFieldList;
            this.showFieldList = this.fixedFieldList.concat(this.defaultSelectedFieldList);
        }
        this.tableKey++;
        this.handleChangeColumnIcon();
    }

    // 获取指令结果信息
    async getInstResultInfo(resultId: string) {
        await this.$axios.post('/instruction/inst/result', { resultId: resultId }).then((res: any) => {
            if (res.list && res.list.length) {
                this.currentRow = res.list[0];
            } else {
                this.currentRow.resultId = resultId;
            }
        });
    }

    // 查看按钮点击
    async handleBtnLook(obj: any) {
        await this.getInstResultInfo(obj.resultId);
        this.$emit('handelOperate', { record: this.currentRow, history: false, clickRecord: this.currentRow });
    }

    // 获取条目组数据
    queryEntryGroupData() {
        this.$axios.get('/entry/group/list').then((res: any) => {
            this.entryGroupList = res;
        });
    }

    // 获取条目标签
    // queryEntryTagData() {
    //     this.$axios
    //         .get('/entryTag/queryAll')
    //         .then((res: any) => {
    //             const filters = res.map(item => {
    //                 return { label: item.dictKeyName, value: item.dictKey };
    //             });
    //             this.itemTagsStorage = filters;
    //             let column = this.tableColumns.find(item => item.id == 'tagIds');
    //             column && (column.filters = filters);
    //             const $xTable = this.$refs['xTable'] as any;
    //             const column2 = $xTable.getColumnByField('tagIds');
    //             if (column2) {
    //                 $xTable.setFilter(column2, filters);
    //             }
    //         })
    //         .catch(err => {
    //             console.log(err, 'queryAll');
    //         });
    // }

    // 重置搜索栏查询条件
    handleReset() {
        this.queryForm.instructionNo = '';
        this.queryForm.dailyInstructionNo = '';
        this.queryForm.batchNo = '';
        this.queryForm.entryCode = '';
        this.queryForm.entryName = '';
        this.queryForm.instStatus = '1';
        this.queryForm.thresholdTypes = [];
        this.queryForm.entryGroups = [];
        this.queryForm.exceedThreshold = false;
        // this.queryForm.tagIds = [];
        // (this.$refs.xTable as any).clearFilter();
        this.handleSetFilters();
    }

    /**
     *  设置表头筛选条件跟查询栏条件保持一致
     */
    handleSetFilters() {
        let fields = ['thresholdType', 'entryCode', 'entryName', 'instructionNo', 'dailyInstructionNo', 'tagIds'];
        this.showFieldList.forEach(ele => {
            if (fields.includes(ele.id)) {
                if (ele.filters) {
                    const column = (this.$refs.xTable as any).getColumnByField(ele.id);
                    if (['thresholdType', 'tagIds'].includes(ele.id)) {
                        const param = ele.id == 'thresholdType' ? 'thresholdTypes' : 'tagIds';
                        const option = column.filters;
                        // 触警类型有值时
                        if (this.queryForm[param] && this.queryForm[param].length) {
                            option.forEach(item => {
                                if (this.queryForm[param].includes(item.value)) {
                                    item.checked = true;
                                } else {
                                    item.checked = false;
                                }
                            });
                        } else {
                            option.forEach(item => {
                                item.checked = false;
                            });
                        }
                    } else {
                        const option = column.filters[0];
                        option.data = this.queryForm[ele.id];
                        if (this.queryForm[ele.id]) {
                            option.checked = true;
                        } else {
                            option.checked = false;
                        }
                    }
                }
            }
        });
        // 修改条件之后，需要手动调用 updateData 处理表格数据
        (this.$refs.xTable as any).updateData();
    }

    // 查询按钮事件
    async handleQuery() {
        this.handleSetFilters();
        await this.queryTableDataList('userAction');
    }

    /**
     * 查询偏离度数据
     */
    async queryTableDataList(operateType: string = 'system') {
        this.tableLoading = true;
        this.$axios
            .post('/deviation/query', { ...this.queryForm, deviationRatio: accDiv(Number(this.deviationValue), 100) }, { headers: { operateType } })
            .then((res: any) => {
                this.tableData = res.list;
                // this.pages.total = res.total;
                this.queryForm.paging.total = res.total;
                this.tableLoading = false;
                this.tableDataKey++;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 修改偏离度
     */
    timer: any = null;
    async setDeviationValue() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
        this.timer = setTimeout(() => {
            let values = getSystem() || [];
            let obj = values.find(item => item.paramKey == 'RISK_RESULT_DEVIATION_VALUE');
            if (obj) {
                obj.paramValue = accDiv(Number(this.deviationValue), 100);
            }
            // 修改系统参数
            setSystem(values);
            // TODO 偏离度标准改变,页面呈现效果改变
            this.queryTableDataList('userAction');
        }, 5000);
    }

    beforeDestroy() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    }

    // 分页查询请求
    handlePageChange() {
        this.queryTableDataList('userAction');
    }

    // 表头搜索
    handleFilterChange(obj: any) {
        const filterList = obj.filterList;
        // 与搜索栏联动字段
        let linkageFields = ['thresholdType', 'entryCode', 'entryName', 'instructionNo', 'dailyInstructionNo', 'tagIds'];
        linkageFields.forEach(ele => {
            let exist = filterList.some(item => item.property == ele);
            if (!exist) {
                if (ele == 'thresholdType') {
                    this.queryForm.thresholdTypes = [];
                } else {
                    this.queryForm[ele] = '';
                }
            }
        });
        this.queryForm.batchNo = '';
        this.queryForm.errorMessage = '';
        this.queryForm.fundCode = '';
        this.queryForm.fundName = '';
        this.queryForm.fundAccountCode = '';
        this.queryForm.fundAccountName = '';
        this.queryForm.stockCode = '';
        this.queryForm.stockName = '';
        this.queryForm.assetCode = '';
        this.queryForm.assetName = '';
        this.queryForm.compareTypes = [];
        this.queryForm.errorValids = [];
        // this.queryForm.tagIds = [];
        if (filterList.length) {
            filterList.forEach(ele => {
                if (['thresholdType', 'compareType', 'errorValid'].includes(ele.property)) {
                    this.queryForm[ele.property + 's'] = ele?.values;
                } else if (ele.property == 'tagIds') {
                    this.queryForm[ele.property] = ele?.values;
                } else if (ele.property == 'instStatus') {
                    this.queryForm.instStatus = '1';
                } else {
                    this.queryForm[ele.property] = ele?.datas[0] || '';
                }
            });
        }
        // else {
        //     this.queryForm.errorValids = [];
        //     this.queryForm.compareTypes = [];
        // }
        this.queryTableDataList('userAction');
    }

    // 表头排序改变事件
    handleTableSortChange({ property, order }) {
        const sortType = order || '';
        let sortField = '';
        if (sortType) {
            // sortField = this.handleSortField(property, sortType);
            sortField = property;
        } else {
            sortField = '';
        }
        this.queryForm.sort.field = sortField;
        this.queryForm.sort.order = sortType;
        this.queryForm.paging.currentPage = 1;
        // this.queryForm.sort = sort;
        this.queryTableDataList('userAction');
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit() {
        await this.queryLayout();
        this.handleSetFilters();
    }

    /**
     * 改变列图标
     */
    handleChangeColumnIcon() {
        this.$nextTick(() => {
            // 需要改icon的列
            const magnifyingGlass = this.showFieldList.filter(i => i.filterType === 'search').map(i => i.id);
            // const magnifyingGlass = this.selectedFieldList.filter(i => i.filterType === 'search').map(i => i.id);
            // 所有列dom
            const cols = (this.$refs['xTable'] as VueObject).getColumns();
            // 找到需要改icon的列domids
            let magnifyingGlassDomIds = [];
            let temp = [];
            cols.forEach(element => {
                if (magnifyingGlass.includes(element.property)) {
                    magnifyingGlassDomIds.push(element.id);
                } else {
                    temp.push(element.id);
                }
            });
            magnifyingGlassDomIds.forEach(colid => {
                const dom = (this.$refs['xTable'] as VueObject).$el.querySelector(`th[data-colid=${colid}] .vxe-icon--funnel`);
                if (dom) {
                    dom.className = 'vxe-filter--btn el-icon-search';
                }
            });

            temp.forEach(colid => {
                const dom = (this.$refs['xTable'] as VueObject).$el.querySelector(`th[data-colid=${colid}] .vxe-filter--btn`);
                if (dom) {
                    dom.className = 'vxe-filter--btn vxe-icon--funnel';
                }
            });
        });
    }

    // 设置表格列对齐
    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'left');
        }
        return value;
    }

    // 偏离度标准变化时
    handleDeviationRatio(val: string) {
        this.deviationValue = val.replace(/[^\d.]/g, ''); // 清除“数字”和“.”以外的字符
        this.setDeviationValue();
    }

    // 条目编号颜色处理
    getEntryCodeColor(values: any) {
        if (!values) {
            return;
        }
        if (values.length > 3) {
            // 三个以上红色
            return { color: 'red' };
        } else if (values.length < 4 && values.length > 0) {
            // 一至三黄色
            return { color: '#f5a43a' };
        }
    }
}
</script>
<style lang="scss" scoped>
.my-input {
    margin: 10px;
    width: 150px;
}
.risk-deviation-query {
    height: 100%;
    min-width: 1200px;
    background: #fff;
    overflow: auto;
    .deviation-box {
        margin: 15px;
        border: 1px solid #d7d7d7;
    }
    .deviation-search {
        // height: 15vh;
        padding: 10px;
        /deep/ .el-form-item {
            margin-bottom: 0px;
            .el-form-item__label {
                color: black;
            }
        }
        .search-box {
            display: flex;
            justify-content: space-between;
        }
        .el-col-5 {
            width: 19.5%;
            .operate {
                margin-top: 10px;
                display: flex;
                justify-content: end;
            }
            .el-button--mini {
                padding: 7px 10px !important;
            }
        }
        .el-col-4 {
            width: 19.5%;
        }
        .checkBoxItem {
            /deep/ .el-form-item__content {
                margin-left: 50px !important;
            }
            color: #000;
        }
        /deep/ .el-input--mini .el-input__icon {
            line-height: 42px !important;
        }
        /deep/ .el-select__tags {
            flex-wrap: nowrap;
        }

        /deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
            display: flex;
            align-items: center;
            width: 74%;
            max-width: fit-content;
            padding: 3px;
            margin: 2px 0 2px 2px;
            .el-select__tags-text {
                display: inline-block;
                font-size: 12px;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        /deep/ .el-select {
            .el-tag__close.el-icon-close {
                right: 1px;
            }
        }
    }
    .deviation-table {
        height: calc(100vh - 195px);
        .table-box {
            height: calc(100% - 60px);
        }
    }
}
/deep/ .vxe-table .vxe-table--header {
    width: 10px !important;
}
/deep/ .vxe-table--fixed-right-wrapper {
    height: calc(100% - 12px) !important;
}
</style>
<style lang="scss">
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
</style>
